<script setup lang="ts">
import { computed, ref } from 'vue'
import HmList from './components/HmList.vue'
/*
1:布局
2：父组件准备数据
3：父传子，子渲染数据
4：子传父，修改数据
5：计算出总价格
*/
const list = ref<
  {
    id: number
    name: string
    price: number
    num: number
  }[]
>([
  {
    id: 1,
    name: '西瓜',
    price: 4,
    num: 1
  },
  {
    id: 2,
    name: '苹果',
    price: 6,
    num: 2
  },
  {
    id: 3,
    name: '雪梨',
    price: 5,
    num: 3
  }
])

const setNum = (obj: { id: number; value: 1 | -1 }) => {
  const fineItem = list.value.find(item => item.id === obj.id)
  if (fineItem) {
    fineItem.num = fineItem.num + obj.value
  }
}

const total = computed<number>(() => {
  return list.value.reduce((prev, item) => prev + item.num * item.price, 0)
})
</script>

<template>
  <div class="home-page">
    <div class="son">
      <HmList :list="list" @setNum="setNum"></HmList>
      <div>总价:{{ total }}</div>
    </div>
  </div>
</template>

<style scoped>
.son {
  width: 600px;
  margin: 0 auto;
}
</style>
